package com.example.a79273.shandianban;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.a79273.shandianban.adapter.YouLiaoListAdapter;
import com.example.a79273.shandianban.adapter.YouRenPagerAdapter;
import com.example.a79273.shandianban.application.MyApplication;
import com.example.a79273.shandianban.config.NetConfigYouLiao;
import com.example.a79273.shandianban.config.NetConfigYouRen;
import com.example.a79273.shandianban.fragment.MyDialogFragment;
import com.example.a79273.shandianban.model.YouLiaoContent;
import com.example.a79273.shandianban.model.YouRenIndexBean;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.HttpManager;
import org.xutils.ImageManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/*
* "有料"页面
*  */
public class YouLiaoActivity extends BaseActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView back_iv;
    private ViewPager viewPager;
    private RadioGroup subtitles_rg;
    private PullToRefreshListView listView;
    private LinearLayout points_ll;

    private YouRenPagerAdapter pagerAdapter;
    private YouLiaoListAdapter listAdapter;

    private HttpManager httpManager = x.http();
    private ImageManager imageManager = x.image();

    private List<ImageView> pagerData;
    private List<YouRenIndexBean.DataBean.BannerlistBean> banners;
    private String[] subtitles_str;
    private List<YouLiaoContent.DataBean.ListBean> listData;
    private ListView lv;

    private MyDialogFragment dialogFragment;

    private int currentPosition = 0;
    private Callback.Cancelable cancelable;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_you_liao);
        initView();
        initData();
        setData();
        setListener();
    }


    private void setListener() {
        back_iv.setOnClickListener(this);
        viewPager.addOnPageChangeListener(this);
        subtitles_rg.setOnCheckedChangeListener(this);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData(currentPosition);
                listView.setRefreshing(true);
            }
        });
        listView.setOnItemClickListener(this);
    }

    private void setData() {
        viewPager.setAdapter(pagerAdapter);
        listView.setAdapter(listAdapter);
    }

    private void initData() {
        dialogFragment = new MyDialogFragment();

        pagerData = new ArrayList<>();
        banners = new ArrayList<>();
        pagerAdapter = new YouRenPagerAdapter(pagerData);
        httpManager.get(new RequestParams(NetConfigYouLiao.BANNER_URL), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                YouRenIndexBean indexBean = YouRenIndexBean.objectFromData(MyApplication.dealWithString(result));
                if (indexBean != null) {
                    banners.addAll(indexBean.getData().getBannerlist());

                    points_ll.setWeightSum(banners.size());
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                    params.setMargins(5, 0, 5, 0);
                    ImageView point;
                    for (YouRenIndexBean.DataBean.BannerlistBean banner : banners) {
                        final ImageView imageView = new ImageView(YouLiaoActivity.this);
                        point = new ImageView(YouLiaoActivity.this);
                        point.setImageResource(R.drawable.point);
                        point.setLayoutParams(params);

                        imageManager.bind(imageView, NetConfigYouRen.ROOT_URL + banner.getPic_scr(), new CommonCallback<Drawable>() {
                            @Override
                            public void onSuccess(Drawable result) {
                                imageView.setOnClickListener(YouLiaoActivity.this);
                                pagerData.add(imageView);
                                if (pagerData.size() == banners.size()) {
                                    pagerAdapter.notifyDataSetChanged();
                                    pointChange(0);
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                Toast.makeText(YouLiaoActivity.this, "网络错误,请检查网络", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onCancelled(CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(YouLiaoActivity.this, "网络错误,请检查网络", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        subtitles_str = getResources().getStringArray(R.array.youLiaoSubtitles);
        for (int i = 0; i < subtitles_rg.getChildCount(); i++) {
            RadioButton radioButton = (RadioButton) subtitles_rg.getChildAt(i);
            radioButton.setText(subtitles_str[i]);
        }

        listData = new ArrayList<>();
        RadioButton child = (RadioButton) subtitles_rg.getChildAt(0);
        child.setChecked(true);
        child.setTextColor(Color.RED);
        listAdapter = new YouLiaoListAdapter(YouLiaoActivity.this, listData);
        loadData(0);
    }

    private void initView() {
        back_iv = (ImageView) findViewById(R.id.iv_youLiao_back);
        View headerView = View.inflate(this, R.layout.headview_youliao, null);
        viewPager = (ViewPager) headerView.findViewById(R.id.vp_youLiao_pages);
        subtitles_rg = (RadioGroup) headerView.findViewById(R.id.rg_youLiao_subtitles);
        points_ll = (LinearLayout) headerView.findViewById(R.id.ll_youLiao_points);

        listView = (PullToRefreshListView) findViewById(R.id.lv_youLiao_content);

        lv = listView.getRefreshableView();
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        lv.addHeaderView(headerView);
        listView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void pointChange(int position) {
        for (int i = 0; i < points_ll.getChildCount(); i++) {
            View child = points_ll.getChildAt(i);
            if (i == position) {
                child.setEnabled(true);
            } else {
                child.setEnabled(false);
            }

        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pointChange(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {
            RadioButton child = (RadioButton) group.getChildAt(i);
            if (child.getId() == checkedId) {
                child.setTextColor(Color.RED);
                loadData(i);
            } else {
                child.setTextColor(Color.BLACK);
            }

        }
    }

    /*加载数据的方法*/
    private void loadData(int position) {
        if (position != currentPosition) {
            dialogFragment.show(getSupportFragmentManager(), "dialog");
            if (cancelable != null && !cancelable.isCancelled()) {
                cancelable.cancel();
                if (listView.isRefreshing()) {
                    listView.onRefreshComplete();
                }
            }
        }
        currentPosition = position;
        listData.clear();//清空数据源
        cancelable = httpManager.get(new RequestParams(String.format(NetConfigYouLiao.CONTENT_URL, position + 1)), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                YouLiaoContent content = YouLiaoContent.objectFromData(MyApplication.dealWithString(result));
                if (content != null) {
                    listData.addAll(content.getData().getList());
                    listAdapter.notifyDataSetChanged();
                    if (listView.isRefreshing()) {
                        listView.onRefreshComplete();
                    }
                    if (dialogFragment.isResumed()) {
                        dialogFragment.dismiss();
                    }
                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v != null) {
            switch (v.getId()) {
                case R.id.iv_youLiao_back:
                    finish();
                    break;
                default:
                    if (banners != null && banners.size() != 0) {
                        YouRenIndexBean.DataBean.BannerlistBean bannerlistBean;
                        String pic_text;
                        int index = pagerData.indexOf(v);
                        bannerlistBean = banners.get(index);
                        pic_text = bannerlistBean.getPic_text().trim();
                        String pic_id = bannerlistBean.getPic_id().trim();
                        Intent intent = null;
                        switch (pic_text) {
                            case "-1":
                                break;
                            case "0":
                                intent = new Intent(this, DesignerInfoActivity.class);
                                //TODO,要传入"设计师介绍"页面的数据
                                intent.putExtra("designerId", pic_id);
                                break;
                            case "4":
                                intent = new Intent(this, YouLiao02Activity.class);
                                intent.putExtra("designerId", pic_id);
                                intent.putExtra("source", "banner");
                                break;
                            case "5":
                                intent = new Intent(this, WebActivity.class);
                                intent.putExtra("pic_id", pic_id);
                                break;
                        }
                        startActivity(intent);
                    }
                    break;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (listData != null && listData.size() != 0) {
            YouLiaoContent.DataBean.ListBean listBean = listData.get(position-2);
            String designerId = listBean.getId();
            String urlPart = listBean.getHref().trim();
            Intent intent = new Intent(this, YouLiao02Activity.class);
            intent.putExtra("urlPart", urlPart);
            intent.putExtra("designerId", designerId);
            intent.putExtra("source", "listItem");
            startActivity(intent);
        }
    }
}
